package com.ceadeal.admin.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述: JSON 数据工具类
 * <p>
 * 作者: wangjh
 * 日期: 2017/1/15 10:34
 */
public class JsonUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);

    public JsonUtils() {
    }

    public static <T> T parseJSON(String json, Class<T> t) {

        ObjectMapper om = new ObjectMapper();
        T result = null;
        try {
            result = (T) om.readValue(json, t);
        } catch (IOException e) {
            LOGGER.error("parse json exception", e);
        }
        return result;
    }

    public static <T> T parseJSON(InputStream is, Class<T> t) {

        ObjectMapper om = new ObjectMapper();
        T result = null;
        try {
            result = (T) om.readValue(is, t);
        } catch (IOException e) {
            LOGGER.error("parse json exception", e);
        }
        return result;
    }

    public static <T> T parseJSON(String json, TypeReference<T> t) {
        ObjectMapper om = new ObjectMapper();
        T result = null;
        try {
            result = om.readValue(json, t);
        } catch (IOException e) {
            LOGGER.error("parse json exception", e);
        }
        return result;
    }

    public static String toJSONString(Object o) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            LOGGER.error("toJSONString exception", e);
        }
        return null;
    }
}
